<template>
	<el-form ref="ruleFormRef" :model="formInline" :rules="formRules" label-width="auto" label-position="top"
		v-loading="isLoading">
		<el-row :gutter="30">
			<re-col :value='12' :xs='12' :sm='24'>
				<el-form-item :label='titles?.unityId' prop='unityId'>
					<el-tree-select clearable v-model='formInline.unityId' v-bind="$attrs" :data="datas" :props="propss"
						:render-after-expand="false" check-strictly :placeholder='prompt?.unityId' @change="treeChange"
						@clear="clearTree" />
				</el-form-item>

			</re-col>
			<re-col :value='12' :xs='12' :sm='24'>
				<el-form-item :label='titles?.userId' prop='userId'>
					<el-select @clear="clearUser" @change="userchange" clearable v-model="formInline.userId"
						:placeholder='prompt?.userId' style="width: 100%" filterable remote
						:remote-method="remoteMethod" :loading="loading" remote-show-suffix>
						<el-option v-for="item in options" :key="item.id" :label="item.nickname" :value="item.id" />
					</el-select>
				</el-form-item>
			</re-col>




			<re-col :value='12' :xs='12' :sm='24'>
				<el-form-item :label='titles?.familyId' prop=''>
					<!-- <familySelect v-model='formInline.familyId' clearable :placeholder='prompt?.familyId'
						:style='{ width: "100%" }'>

					</familySelect> -->
					<el-select @clear="clearFamily" v-model="family" clearable filterable allow-create
						default-first-option :reserve-keyword="false" placeholder="请选择家庭" style="width: 100%"
						@change="familychange">
						<el-option v-for="item in familyoptions" :key="item.id" :label="item.familyName"
							:value="item.id" />
					</el-select>
				</el-form-item>
			</re-col>
			<re-col :value='12' :xs='12' :sm='24'>
				<el-form-item :label='titles?.roomId' prop='room'>
					<el-select v-model="room" @clear="clearRoom" clearable filterable allow-create default-first-option
						:reserve-keyword="false" placeholder="请选择房间" style="width: 100%" @change="roomchange">
						<el-option v-for="item in roomoptions" :key="item.id" :label="item.roomName" :value="item.id" />
					</el-select>
					<!-- <el-input v-model.trim='formInline.roomId' clearable :placeholder='prompt?.roomId' /> -->
				</el-form-item>
			</re-col>
			<!-- @blur="deviceSNblur"  -->
			<re-col :value='12' :xs='12' :sm='24'>
				<el-form-item :label='titles?.deviceSN' prop='deviceSN'>
					<el-input :minlength="10" :maxlength="16":show-word-limit="true" v-model.trim='formInline.deviceSN' clearable
						:placeholder='prompt?.deviceSN'> <template #append>
							<el-button @click="devicechange" :icon="Search" />
						</template>
					</el-input>
				</el-form-item>
			</re-col>
			<re-col :value='12' :xs='12' :sm='24' v-loading.fullscreen.lock="loadings">
				<el-form-item :label='titles?.productId' prop='productId'>
					<div>
						<el-tag type="info" v-if="formInline.productId == 0">暂无产品信息</el-tag>
						<el-tag type="primary" v-if="formInline.productId !== 0">
							{{ isNullOrEmpty(formInline.productName) }}
						</el-tag>

					</div>


					<!-- <el-input v-model.trim='formInline.productName' clearable :placeholder='prompt?.productId' /> -->
				</el-form-item>
			</re-col>

			<re-col :value='12' :xs='12' :sm='24'>
				<el-form-item :label='titles?.flowCardId' prop=''>

					<el-input :minlength="10" :maxlength="16" 
					@blur="flowCardchange" 
					:show-word-limit="true"
						v-model.trim='formInline.flowCardNum' clearable 
						:placeholder='prompt?.flowCardId'
						>
						<!-- <template #append>
							<el-button @click="flowCardchange" :icon="Search" />
						</template> -->
					</el-input>
				</el-form-item>
			</re-col>
			<!-- <re-col :value='12' :xs='12' :sm='24' >
				<el-form-item label='流量卡信息' prop=''>
					<el-tag type="danger" v-if="flowCardStatus == 0">无流量卡信息</el-tag>
					<el-tag type="primary" v-if="flowCardStatus == 1">流量卡已使用</el-tag>
					<el-tag type="success" v-if="flowCardStatus == 2">流量卡可用</el-tag>
				</el-form-item>
			</re-col> -->
			<re-col :value='12' :xs='12' :sm='24'>
				<el-form-item :label='titles?.deviceName' prop='deviceName'>
					<el-input :maxlength="30" :show-word-limit="true" v-model.trim='formInline.deviceName' clearable
						:placeholder='prompt?.deviceName' />
				</el-form-item>
			</re-col>

			<re-col :value='12' :xs='12' :sm='24'>
				<el-form-item :label='titles?.noticeStatus' prop='noticeStatus'>

					<el-switch @change="switchStatus" v-model="formInline.noticeStatus" :active-value="1"
						:inactive-value="2" />
				</el-form-item>
			</re-col>
		</el-row>
	</el-form>
</template>

<script setup lang="ts">
import { isNullOrEmpty } from '@/utils/functions'
import { ref, reactive } from "vue";
import ReCol from "@/components/ReCol";
import type { FormRules } from "element-plus";
import { titles, prompt } from './index';
import { getUnitTree } from '@/api/manage/units-manager/units-manager/index';
import type { infoType } from '@/api/manage/Individual-management/device-management/index';
import { getProductInfo, getProductFlow } from '@/api/manage/Individual-management/device-management/index';
import { ElMessage, } from "element-plus";
import { usePageVariablesStoreHook } from '@/store/modules/pageVariables'
import { getIndivduaiSelectList } from '@/api/manage/Individual-management/Individual-users/index';
import { getFamilySelectList, getRoomSelectList } from '@/api/manage/Individual-management/Individual-management/index';
import { FLOWCARD_REG, DEVICESN_REG } from '@/constant/index'
import { Search } from '@element-plus/icons-vue'
type FormProps = {
	formInline: infoType,
	isLoading: boolean,
	type: number
}
const roomoptions = ref([

])
const loadings = ref(false) //点击查询序列号时触发
let timer = null;
const familyoptions = ref([])
const options = ref([])
const list = ref([])
const loading = ref(false)
const props = withDefaults(defineProps<FormProps>(), {
	formInline: () => ({} as infoType),
	isLoading: false,
	type: 1
});
const datas = ref([]);
const propss = {
	label: 'unityName',
	value: 'id',
	children: 'childs',
}
const room = ref(null)
const family = ref(null)
const formRules = reactive(<FormRules>{
	unityId: [{ required: true, message: prompt?.unityId, trigger: 'blur' },],
	userId: [{ required: true, message: prompt?.userId, trigger: 'blur' },],
	family: [{ required: true, message: '请选择家庭', trigger: 'blur' },],
	deviceSN: [{ required: true, message: prompt?.deviceSN, trigger: 'blur' }, { pattern: DEVICESN_REG.role, message: DEVICESN_REG.text, trigger: 'blur' }],
	// flowCardNum: [
	// {
	// 	validator: (rule, value, callback) => {
	// 		if (value) {
	// 			let regex = /^[a-zA-Z0-9]{10,16}$/
	// 			callback(new Error('流量卡号不能重复'));
	// 		} else {
	// 			callback();
	// 		}

	// 	},
	// 	trigger: "blur"
	// }],

});
const ruleFormRef = ref();
function getRef() {
	return ruleFormRef.value;
}

onMounted(() => {
	setTimeout(() => {
		if (props.type == 1) {
			props.formInline.productId = 0
		}

	}, 100)

})

//监听流量卡输入框
watch(() => props.formInline.flowCardNum, (val) => {
	if (props.formInline.flowCardNum == "") {
		props.formInline.flowCardId = 0
	}
})
// 监听监管单位获取个体用户
watch(() => props.formInline.unityId, (val) => {
	if (props.formInline.unityId !== null && props.formInline.unityId !== '' && props.formInline.unityId !== undefined) {
		getIndivduaiSelectList({
			unityId: props.formInline.unityId
		}).then(res => {
			// console.log("dff",res);

			list.value = res.result.users
			options.value = list.value
		})
	}


}, {
	deep: true,
	immediate: true
})

//监听个体用户获取家庭下拉框
watch(() => props.formInline.userId, (val) => {
	if (props.formInline.userId !== null && props.formInline.userId !== '' && props.formInline.userId !== undefined) {
		getFamilySelectList({ userId: props.formInline.userId }).then(res => {
			// list.value = res.result.data
			familyoptions.value = res.result.data
			family.value = props.formInline.familyId
			// console.log("family.value",family.value);



		})
	}

}, {
	deep: true,
	immediate: true
})
//监听家庭获取房间号
watch(() => props.formInline.familyId, (val) => {
	if (props.formInline.familyId !== null && props.formInline.familyId !== '' && props.formInline.familyId !== undefined) {
		getRoomSelectList({ familyId: props.formInline.familyId }).then(res => {

			if (props.formInline.roomId == 0) {
				props.formInline.roomName = ''
				props.formInline.roomId = null
			} else {
				room.value = props.formInline.roomId

			}

			roomoptions.value = res.result.data
		})
	}

}, {
	deep: true,
	immediate: true
})
const clearTree = () => {
	props.formInline.userId = ''

	props.formInline.familyId = ''
	props.formInline.familyName = ''
	family.value = ''

	props.formInline.roomName = ''
	props.formInline.roomId = ''
	room.value = ''
}
const clearUser = () => {
	props.formInline.familyId = ''
	props.formInline.familyName = ''
	family.value = ''

	props.formInline.roomName = ''
	props.formInline.roomId = ''
	room.value = ''
}

const clearFamily = () => {
	props.formInline.roomName = ''
	props.formInline.roomId = null
	room.value = null
	// console.log("ee",family.value);

}


const clearRoom = () => {
	props.formInline.roomName = ''
	props.formInline.roomId = null
	// console.log("ee",room.value);

}

getUnitTree({ unityId: usePageVariablesStoreHook().getManage()?.unityId }).then(res => {
	datas.value.push(...res.result.data)
})

const treeChange = (e) => {
	// console.log("foofh", e);
	props.formInline.userId = null
	getIndivduaiSelectList({
		unityId: e
	}).then(res => {
		list.value = res.result.users
		options.value = list.value
	})
}
const remoteMethod = (query) => {
	if (query) {
		loading.value = true
		setTimeout(() => {
			loading.value = false
			options.value = list.value.filter((item) => {
				return item.familyName.includes(query)
			})
		}, 100)
	} else {
		options.value = list.value
	}
}
//个体下拉框
const userchange = (e) => {
	props.formInline.familyId = ''
	props.formInline.familyName = ''
	family.value = ''

	props.formInline.roomName = ''
	props.formInline.roomId = ''
	room.value = ''
}
//房间下拉框change
const roomchange = (e) => {
	room.value = e
	if (typeof e == 'string') {
		props.formInline.roomName = e
		props.formInline.roomId = null
	} else {
		props.formInline.roomId = e
		props.formInline.roomName = null
	}
}

//家庭下拉框change
const familychange = (e) => {
	family.value = e
	props.formInline.family = e
	roomoptions.value = []
	props.formInline.roomName = ''
	props.formInline.roomId = ''
	room.value = ''

	if (typeof e == 'string') {
		props.formInline.familyName = e
		props.formInline.familyId = ''
	} else {
		props.formInline.familyId = e
		props.formInline.familyName = null
	}
}


function throttle(fn, delay) {
	if (timer == null) {
		timer = setTimeout(() => {
			fn();
			clearTimeout(timer);
			timer = null;
			// props.formInline.deviceSN = undefined;
		}, delay);
	}
}
const devicechange = e => {
	loadings.value = true
	console.log("loadings.value", loadings.value);

	if (e == null || e.length < 10) {
		loadings.value = false
		return;
	} else {
		throttle(deviceSNblur, 2000);

	}

};
const flowCardchange = e => {
	if (e == null || e.length < 10) {

		return;
	} else {
		throttle(flowCardblur, 100);
	}
};
const switchStatus = (e) => {
	// console.log('开关状态', e, props.formInline.noticeStatus);
}

const deviceSNStatus = ref(0)
const deviceSNblur = () => { //失去焦点出发获取序列号
	// console.log('获取序列号', props.formInline.deviceSN);
	getProductInfo({
		deviceSN: props.formInline.deviceSN
	}).then(res => {
		loadings.value = false
		// console.log('获取序列号', res);
		deviceSNStatus.value = res.result.snStatus
		props.formInline.productId = res.result.productId
		props.formInline.modelId = res.result.modelId
		props.formInline.productName = res.result.productName
		// if (res.result.snStatus == 2) {
		// 	return
		// } else {
		// 	if (res.result.snStatus == 0) {
		// 		ElMessage({
		// 			type: 'error',
		// 			message: '序列号错误',
		// 		})
		// 	} else {
		// 		ElMessage({
		// 			type: 'error',
		// 			message: '序列号已使用',
		// 		})
		// 	}
		// }
	})
}

const flowCardStatus = ref(0)
const flowCardblur = () => {  //使用状态1已使用2未使用
	if(props.formInline.flowCardNum.replace(/^[a-zA-Z0-9]{10,16}$/,'')){
		ElMessage({
					type: 'error',
					message: '流量卡号为10-16位字母或数字组合',
				})
				return
	}
	// console.log('', props.formInline.deviceSN);
	getProductFlow({
		flowCardNum: props.formInline.flowCardNum
	}).then(res => {
		console.log('流量卡号', res);
		flowCardStatus.value = res.result.status

		// props.formInline.productName = res.result.productName
		if (res.result.status == 2) {
			props.formInline.flowCardId = res.result.flowCardId
			return
		}
		//  else {
		// 	if (res.result.status == 0) {
		// 		ElMessage({
		// 			type: 'error',
		// 			message: '流量卡号错误',
		// 		})
		// 	} else {
		// 		ElMessage({
		// 			type: 'error',
		// 			message: '流量卡已使用',
		// 		})
		// 	}
		// }
	})
}

defineExpose({ getRef });
</script>
